import React, { Component } from "react";
import "./goodsDetail.scss";
// 引入axios
import myAxios from "../../utils/myAxios";
import { NavBar, Icon, Carousel, Toast } from "antd-mobile";
class goodsDetail extends Component {
  state = {
    data: {},
    imgHeight: 250,
    showSwiper: false,
    showCollect: false, // 默认没有收藏为false
  };
  // 点击收藏
  collectClick = (params) => {
    // 先获取localStorage
    let collections_str = localStorage.getItem("collections");
    // 转成对象
    let collections = JSON.parse(collections_str || "[]");
    // findIndex是遍历数组的一个方法
    var index = collections.findIndex((v) => {
      if (v.goods_id == this.state.data.goods_id) {
        return true;
      }
    });
    if (index != -1) {
      // 说明已经收藏过了，这次点击要取消收藏
      collections.splice(index, 1);
      this.setState({
        showCollect: false,
      });
      Toast.info("已取消收藏!", 1);
    } else {
      // 没有被收藏过，这次点击要添加收藏，把数据添加到localStorage中
      collections.push(this.state.data);
      this.setState({
        showCollect: true,
      });
      Toast.info("收藏成功!", 1);
    }
    localStorage.setItem("collections", JSON.stringify(collections));
  };
  // 点击购物车，跳转到购物车页面
  toCart = (params) => {
    this.props.history.push("/cart");
  };
  // 点击加入购物车，在本地存储购物车
  addCart = (params) => {
    let carts_str = localStorage.getItem("carts");
    let carts = JSON.parse(carts_str || "[]");
    // 获取本商品的id信息
    // let goods_id = this.data.goods_id
    let goods_id = this.state.data.goods_id
    // 找购物车里面有没有本商品的存在
    let index = carts.findIndex(v=>{
      if(v.goods_id==goods_id){
        // 已经加购过
        return true
      }
    })
    // 判断遍历结果
    if(index!=-1){
      // 有过,index的值为商品在数组里面的索引
      carts[index].num++
    }else{
      // num计数，添加num属性
    //  this.data.num=1
     this.state.data.num=1
      // 设置商品在购物车页面默认是选中状态
      // this.data.checked=true
      this.state.data.checked=true
      // 添加
    //  console.log(this.state.data);
      carts.push(this.data)
    }
    Toast.info('加入购物车成功', 1);
    localStorage.setItem("carts",JSON.stringify(carts))
  };
  // 点击立即购买，跳到支付页面
  payClick = (params) => {
    this.props.history.push("/pay");
  };
  constructor(props) {
    super(props);
    // console.log(props); // 里面有一个match属性，props.match.params可得到对象 {goods_id: "57445"}
  }
  componentDidMount() {
    var { goods_id } = this.props.match.params;
    console.log(goods_id);
    myAxios
      .get("goods/detail", {
        params: {
          goods_id,
        },
      })
      .then((res) => {
        // Toast.loading('页面正在加载...', 0,null,true);
        console.log(res);
        this.data = res;
        this.setState({
          data: res,
          showSwiper: true,
        });
      });
  }
  render() {
    return (
      <div className="app-detail">
        <NavBar
          icon={<Icon type="left" />}
          onLeftClick={() => window.history.back(1)}
          className="detail-con"
        >
          商品详情
        </NavBar>
        {/* 轮播图 */}
        <div className="detail-carousel">
          {/* 轮播优化 */}
          {this.state.showSwiper && (
            <Carousel autoplay={true} infinite>
              {this.state.data.pics &&
                this.state.data.pics.map((val) => (
                  <div
                    key={val}
                    style={{
                      display: "inline-block",
                      width: "100%",
                      height: this.state.imgHeight,
                    }}
                  >
                    <img
                      src={val.pics_mid}
                      alt="网络不佳"
                      style={{ width: "80%", verticalAlign: "top" }}
                      onLoad={() => {
                        // fire window resize event to change height
                        window.dispatchEvent(new Event("resize"));
                        this.setState({ imgHeight: 250 });
                      }}
                    />
                  </div>
                ))}
            </Carousel>
          )}
        </div>
        {/* 价格 */}
        <div className="detail-price">
          <div className="price">
            ￥<span>{this.state.data.goods_price}</span>
          </div>
          <div className="share-collect">
            <i className="iconfont icon-fenxiang"></i>
            <i
              className={
                this.state.showCollect
                  ? "iconfont icon-shoucang active"
                  : "iconfont icon-shoucang"
              }
              onClick={this.collectClick}
            ></i>
          </div>
        </div>
        {/* 标题 */}
        <div className="detail-title">{this.state.data.goods_name}</div>
        {/* 图文详情 */}
        {/* 富文本位置 */}
        <div className="detail-image-text">
          <div className="image-text-title">图文详情</div>
          <div
            className="image-text-content"
            dangerouslySetInnerHTML={{
              __html: this.state.data.goods_introduce,
            }}
          ></div>
        </div>
        {/* 底部 */}
        <div className="detail-bottom">
          <div className="bottom-connect">
            <i className="iconfont icon-kefu"></i>
            <span>联系客服</span>
          </div>
          <div className="bottom-cart" onClick={this.toCart}>
            <i className="iconfont icon-icon-"></i>
            <span>购物车</span>
          </div>
          <div className="bottom-join-cart" onClick={this.addCart}>
            加入购物车
          </div>
          <div className="bottom-buy" onClick={this.payClick}>
            立即购买
          </div>
        </div>
      </div>
    );
  }
}
export default goodsDetail;
